package com.netty.server.console;


import org.apache.log4j.Logger;

import utl.mofen.jsonStreamHandler.HandlerFactory;
import utl.mofen.jsonStreamHandler.IJSonStreamHandler;
import utl.mofen.objects.JSonStream;
import utl.mofen.utils.IntfUtil;

import com.netty.handler.IJSonStreamNettyHandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.channel.ChannelOption;

public class NettyServerHandler extends ChannelInboundMessageHandlerAdapter<JSonStream> {
	private static final Logger logger = Logger.getLogger(NettyServerHandler.class);
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.channel().config().setOption(ChannelOption.SO_KEEPALIVE, true);
		NettyChannels.add(ctx.channel());       
		
		StringBuffer sb = new StringBuffer();
		sb.append("ChannelID:").append(ctx.channel().id() + "连接!");
		sb.append("当前连接数:").append(NettyChannels.getCount());
		logger.info(sb.toString());
		sb = null;
    }
	
	@Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("ChannelID:").append(ctx.channel().id() + "断开!");
		sb.append("当前连接数:").append(NettyChannels.getCount());
		logger.info(sb.toString());
		NettyChannels.remove(ctx.channel());
		sb = null;
    }
	
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        System.out.println(cause.getMessage());      
        ctx.close();
    }
    
    
	@Override
	public void messageReceived(ChannelHandlerContext ctx, JSonStream jsonStream)
			throws Exception {
		try
		{
			IJSonStreamHandler handler = HandlerFactory.createHandler(jsonStream);	
		    if (IntfUtil.isInterface(handler.getClass(), IJSonStreamNettyHandler.class))
		    {		    	
		    	((IJSonStreamNettyHandler)handler).setChannelHandlerContext(ctx);		    	
		    }
			handler.setJSonStream(jsonStream);
			handler.doAction();	
			handler = null;
		}catch (Exception e)
		{
			jsonStream.setResultMsg(e.getMessage());
			jsonStream.setResult(false);
			e.printStackTrace();
		}
		ctx.write(jsonStream);
	}
}
